package cn.edu.gdgm.system.controller;

import cn.edu.gdgm.system.dto.Result;
import cn.edu.gdgm.system.entity.MedicinalData;
import cn.edu.gdgm.system.entity.Slot;
import cn.edu.gdgm.system.mapper.MedicinalDataMapper;
import cn.edu.gdgm.system.service.ISlotService;
import cn.fightingguys.security.web.wechat.entity.WeChatMiniProgramUserDetails;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author quan
 * @date 2021-03-06
 */
@Api(tags = {"药品Controller"})
@RestController
@RequestMapping("/slot")
public class SlotController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private ISlotService slotService;

    @Resource
    private MedicinalDataMapper mapper;


    @PostMapping("/scan")
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "扫描添加药品")
    public Result scan(Slot slot) {
        // 如果该仓位已经添加过则更新
        QueryWrapper<Slot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_uuid", slot.getDeviceUuid()).eq("slot_id", slot.getSlotId());
        Slot alreadySlot = slotService.getOne(queryWrapper);
        if (alreadySlot != null && StringUtils.isNotBlank(alreadySlot.getId())) {
            slot.setId(alreadySlot.getId());
        }
        // 查看该条形码是否存在数据，如果有就查询该药品名称，没有就填充为 药品+条形码
        MedicinalData medicinal = mapper.selectOne(new QueryWrapper<MedicinalData>().eq("code", slot.getCertificateCode()));
        if (medicinal != null && StringUtils.isNotBlank(medicinal.getName())) {
            slot.setMedicinalName(medicinal.getName());
        } else {
            slot.setMedicinalName("药品" + slot.getCertificateCode());
        }
        return toResult(slotService.saveOrUpdate(slot));
    }

    @GetMapping()
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "查看当前用户的药品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceUuid", value = "设备UUID唯一识别号"),
    })
    public Result list(@RequestParam String deviceUuid) {
        QueryWrapper<Slot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_uuid", deviceUuid).orderByAsc("slot_id");
        List<Slot> data = slotService.list(queryWrapper);
        return Result.success(data);
    }

    @DeleteMapping()
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "删除药品（清空该药仓）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "药仓ID"),
    })
    public Result delete(@RequestParam String id, @ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails) {
        boolean rs = slotService.removeById(id);
        return toResult(rs);
    }

    private Result toResult(boolean b) {
        if (b) {
            return Result.success("操作成功");
        } else {
            return Result.error(201, "操作失败");
        }
    }
}
